# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
from datetime import datetime
from django.db.models.signals import post_save
from django.dispatch import receiver


class WeChatAccount(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    nickName = models.CharField(max_length=100, null=True, blank=False)
    avatarUrl = models.CharField(max_length=255, null=True, blank=False)
    openId = models.CharField(max_length=255, null=True, blank=False)
    unionId = models.CharField(max_length=100, null=True, blank=False)
    gender = models.CharField(max_length=100, null=True, blank=False)
    city = models.CharField(max_length=100, null=True, blank=False)
    province = models.CharField(max_length=100, null=True, blank=False)
    country = models.CharField(max_length=100, null=True, blank=False)
    session_key = models.CharField(max_length=255, null=True, blank=False)

    def __str__(self):
        try:
            return self.nickName
        except User.DoesNotExist:
            return self.gender


@receiver(post_save, sender=User)
def create_wechat_user(sender, instance, created, **kwargs):
    if created:
        wechat = WeChatAccount()
        wechat.user = instance
        wechat.save()
        # WeChatAccount.objects.create(user=instance, nickName='')


class Shop(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    shop_name = models.CharField(max_length=100)
    address = models.CharField(max_length=255)
    phone = models.CharField(max_length=50)
    avatar = models.URLField(default=0, null=True)
    business_hours = models.CharField(max_length=50)
    is_open = models.IntegerField()
    details = models.CharField(max_length=255)

    def __repr__(self):
        return self.shop_name


class Type(models.Model):
    id = models.AutoField(primary_key=True)
    attr = models.CharField(max_length=100)
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE)


class Catalogue(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    image = models.URLField()
    price = models.IntegerField()
    detail = models.CharField(max_length=255)
    tid = models.ForeignKey(Type, on_delete=models.CASCADE)

    def __repr__(self):
        return self.name


class Orders(models.Model):
    id = models.AutoField(primary_key=True)
    oid = models.CharField(max_length=50)
    desk = models.CharField(max_length=8)
    create_time = models.DateTimeField(auto_now_add=True)
    food = models.ForeignKey(Catalogue, on_delete=models.CASCADE)
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)